﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace ExFlash.Tags
{
    public class DefineSpriteTag : Tag, IHasCharacterId, ITagContainer
    {
        private readonly int _swfVersion;
        private readonly Dictionary<ushort, Tag> _idDictionary; 

        public ushort SpriteId
        {
            get;
            protected set;
        }

        public ushort FrameCount
        {
            get;
            protected set;
        }

        public List<Tag> ControlTags
        {
            get;
            protected set;
        }

        public DefineSpriteTag(int len, int version, int offset)
            : base(TagCodes.DefineSprite, len, offset)
        {
            _swfVersion = version;
            _idDictionary = new Dictionary<ushort, Tag>();
        }

        public override void SwfDeserialize(BinaryBitReader reader)
        {
            SpriteId = reader.ReadUInt16();

            FrameCount = reader.ReadUInt16();

            ControlTags = new List<Tag>();

            TagAssistant tagAss = new TagAssistant(reader, _swfVersion, _idDictionary);

            try
            {
                tagAss.PopulateTags(ControlTags);
            }
            catch (Exception ex)
            {
                throw new SerializationException("Failed to deserialize tag in DefineSprite", ex);
            }
        }

        public override void SwfSerialize(byte[] arr, ref int offset)
        {
            throw new NotImplementedException();
        }

        #region IHasCharacterID Members

        public ushort Id
        {
            get { return SpriteId; }
        }

        #endregion

        #region Implementation of ITagContainer

        public IEnumerable<Tag> Tags
        {
            get
            {
                foreach (Tag tag in ControlTags)
                {
                    yield return tag;
                }
            }
        }

        public void AddIdsToDictionary(IDictionary<ushort, Tag> dict)
        {
            foreach (KeyValuePair<ushort, Tag> keyValuePair in _idDictionary)
            {
                dict.Add(keyValuePair);
            }
        }

        #endregion
    }
}
